package api

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/h2non/filetype"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/respx"
	"zhonghui/console/warehouse/servicex"
	"zhonghui/console/warehouse/structx"
)

func (server *Server) Upload(c *gin.Context) {
	file, header, err := c.Request.FormFile("image_upload")
	if err != nil {
		logx.ZapTrace(c).Errorw("FormFile", "err", err)
		respx.Alert(c, "上传文件错误")
		return
	}
	buf, _ := ioutil.ReadAll(file)

	if !filetype.Is(buf, "jpg") &&
		!filetype.Is(buf, "png") &&
		!filetype.Is(buf, "gif") {
		respx.Alert(c, "仅支持jpg、png、gif")
		return
	}

	if header.Size > helperx.MB*10 {
		respx.Alert(c, "仅支持10M大小以下的图片")
		return
	}
	suffix := "." + header.Header.Get("Content-Type")[6:]
	fixFileName := strconv.FormatInt(time.Now().UnixNano(), 10) + helperx.EasyMD5(header.Filename) + suffix
	defer file.Close()

	var dstPrePath, bucket string

	fileType, _ := c.GetQuery("file_type")
	switch fileType {
	case "fund":
		dstPrePath = fmt.Sprintf("fund/images/%s/", time.Now().Format(helperx.TimeLayoutYmd))
		bucket = "safe"
	case "avatar":
		dstPrePath = fmt.Sprintf("fund/avatars/%s/", time.Now().Format(helperx.TimeLayoutYmd))
		bucket = "normal"
	default:
		respx.Alert(c, "业务类型不支持")
		return
	}

	oc, err := servicex.OssClient(bucket)
	if err != nil {
		logx.ZapTrace(c).Errorw("初始化OSS错误", "err", err)
		respx.Alert(c, "初始化OSS错误")
		return
	}

	if err := oc.OssPutBucket(dstPrePath+fixFileName, bytes.NewReader(buf)); err != nil {
		logx.ZapTrace(c).Errorw("PutObject", "err", err)
		respx.Alert(c, "上传失败")
		return
	}

	obj, _ := oc.OssFullPath(dstPrePath+fixFileName, true)

	resp := map[string]interface{}{
		"obj": structx.CommonImageData{
			Thumb: obj.Thumb,
			Large: obj.Large,
		},
		"relative_path": dstPrePath + fixFileName,
	}

	respx.Success(c, resp, nil)
}
